package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpRseponse;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

/**
 * 该线程负责与指定客户端完成HTTP协议的交互过程
 *
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {

        //测试:读取客户端发送过来的内容
        try {
            //1.解析请求
            HttpRequest request = new HttpRequest(socket);
            //创建响应对象
            HttpRseponse rseponse = new HttpRseponse(socket);
            //2.处理请求
            String path = request.getUri();
            System.out.println("抽象路径为:"+path);
            File file = new File("./webapps"+path);
            //如果该资源存在,并且是一个文件 则响应 该文件
            if (file.isFile() && file.exists()) {
                rseponse.setEntity(file);

            }else {//否则响应404
                rseponse.setStatusCode(404);
                rseponse.setStatusReason("NotFound");
                file = new File("./webapps/root/404.html");
                rseponse.setEntity(file);
            }
            //3.发送响应
            rseponse.flush();



        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
